package com.sdtele.tta.servlets;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.Doc;
import com.sdtele.tta.models.User;

@WebServlet("/front/UploadDoc")
@MultipartConfig
public class UploadDoc extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/UploadDocTest.jsp").forward(request, response);

		// doPost(request, response);
	}

	private String getFilename(Part part) {
		String contentDispositionHeader = part.getHeader("content-disposition");
		String[] elements = contentDispositionHeader.split(";");
		for (String element : elements) {
			if (element.trim().startsWith("filename")) {
				String fileName = element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
				return new File(fileName).getName();
			}
		}
		return null;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Map<String, String> inputMap = new HashMap<String, String>();
		Map<String, String> errorMap = new HashMap<String, String>();
		request.setAttribute("input", inputMap);
		request.setAttribute("error", errorMap);
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		boolean success = false;
		Collection<Part> parts = request.getParts();
		//	long taskId = Long.parseLong(request.getParameter("taskId"));
		 long taskId = 1741;

		User user = (User) request.getSession().getAttribute("user");
		//	long userId = user.getId();
		 long userId = 0;
		if (parts.size() == 1) {

			Part part = request.getPart("file");

			String fileName = getFilename(part);
			if (fileName != null && (!fileName.isEmpty()))
			// {
			// errorMap.put("file", "请选择文件");
			// }
			// if (errorMap.size() == 0)
			{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String uriPath = "file/" + sdf.format(new Date());
				String physicalPath = getServletContext().getRealPath(uriPath);
				if (!new File(physicalPath).exists()) {
					new File(physicalPath).mkdirs();
				}
				physicalPath += File.separator;
				String fn = UUID.randomUUID().toString();
				physicalPath += fn;
				uriPath += "/" + fn;
				System.out.println("相对路径为：" + uriPath);
				System.out.println("物理路径为：" + physicalPath);
				part.write(physicalPath);
				System.out.println("写文件成功");
				Doc doc = new Doc();
				doc.setName(fileName);
				doc.setPath(uriPath);
				doc.setRealPath(physicalPath);
				doc.setUpdateTime(new Timestamp(new java.util.Date().getTime()));
				// User curUser = Dac.getInstance().getUser(0);
				doc.setUserId(userId);
				doc.setTaskId(taskId);
				System.out.println(doc);
				Dac.getInstance().addDoc(doc);
				if (doc.getId() > 0) {
					success = true;
					Doc docres = Dac.getInstance().getDoc(doc.getId());
					response.setStatus(0);
					response.getWriter().append(new Gson().toJson(docres));
					System.out.println(new Gson().toJson(docres));
				} else {
					response.setStatus(1);
					response.getWriter().append("上传附件失败");
				}
			}

		} else {
			for (Part part : parts) {

				String fileName = getFilename(part);

				if (fileName != null && (!fileName.isEmpty()))
				// {
				// errorMap.put("file", "请选择文件");
				// }
				// if (errorMap.size() == 0)
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String uriPath = "file/" + sdf.format(new Date());
					String physicalPath = getServletContext().getRealPath(uriPath);
					if (!new File(physicalPath).exists()) {
						new File(physicalPath).mkdirs();
					}
					physicalPath += File.separator;
					String fn = UUID.randomUUID().toString();
					physicalPath += fn;
					uriPath += "/" + fn;
					System.out.println("物理路径为：" + physicalPath);
					part.write(physicalPath);
					System.out.println("写文件成功");
					Doc doc = new Doc();
					doc.setName(fileName);
					doc.setPath(uriPath);
					doc.setRealPath(physicalPath);
					doc.setUpdateTime(new Timestamp(new java.util.Date().getTime()));
					// User curUser = Dac.getInstance().getUser(0);
					doc.setUserId(userId);
					doc.setTaskId(taskId);
					System.out.println(doc);
					Dac.getInstance().addDoc(doc);
					if (doc.getId() > 0) {
						success = true;
						Doc docres = Dac.getInstance().getDoc(doc.getId());
						response.getWriter().append(new Gson().toJson(docres));
						System.out.println(new Gson().toJson(docres));
					} else {
						response.setStatus(1);
						response.getWriter().append("上传附件失败");

					}
				}

			}
		}

	}
}
